package com.twu.biblioteca.data;

import com.twu.biblioteca.exceptions.ItemAlreadyCheckedOutException;
import com.twu.biblioteca.exceptions.ItemNotCheckedOutException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by florian on 5/01/14.
 */
public class BibliotecaItemDAO {
    protected final Map<Integer, BibliotecaItem> idToItemMap;

    protected BibliotecaItemDAO(Collection<BibliotecaItem> items) {
        this.idToItemMap = new HashMap<Integer,BibliotecaItem>(items.size());
        for (BibliotecaItem item : items) {
            idToItemMap.put(item.getId(), item);
        }
    }

    public Collection<BibliotecaItem> getAllAvailableItems() {
        Collection<BibliotecaItem> availableItems = new ArrayList<BibliotecaItem>(idToItemMap.size());
        for (BibliotecaItem item : idToItemMap.values()) {
            if (item.isAvailable()) {
                availableItems.add(item);
            }
        }
        return availableItems;
    }


    /**
     * Finds the item with the indicated id or null in case no item with this id exists
     * @param id
     * @return the item or null
     */
    public BibliotecaItem findItemForId(int id) {
        return idToItemMap.get(id);
    }

    public void checkoutItem(BibliotecaItem itemToCheckout, User user) throws ItemAlreadyCheckedOutException {
        if (!itemToCheckout.isAvailable()) {
            throw new ItemAlreadyCheckedOutException();
        }
        if (user==null) {
            throw new IllegalArgumentException("User to check out an Item cannot be null");
        }
        itemToCheckout.setCheckedOutBy(user);
    }

    public void returnItem(BibliotecaItem itemToReturn) throws ItemNotCheckedOutException {
        if (itemToReturn.isAvailable()) {
            throw new ItemNotCheckedOutException();
        }
        itemToReturn.setCheckedOutBy(null);

    }
}
